import { Modal } from "antd";

export function setupGlobalErrorHandler() {
  if (typeof window === "undefined" || window.__GLOBAL_ERROR_HANDLER__) return;
  window.__GLOBAL_ERROR_HANDLER__ = true;

  function showGlobalErrorModal(content) {
    console.log("[全局异常弹窗]", content);
    try {
      Modal.error({
        title: "出错啦",
        content,
        centered: true,
      });
    } catch (e) {
      /* fallback: do nothing */
    }
  }

  window.addEventListener("unhandledrejection", function (event) {
    const reason = event.reason;
    if (reason && typeof reason === "object" && reason.code === 0) {
      showGlobalErrorModal(reason.msg || "请求异常，请稍后重试");
    } else if (
      reason &&
      reason.name === "AxiosError" &&
      reason.response &&
      reason.response.status &&
      reason.response.status !== 200
    ) {
      showGlobalErrorModal(
        reason.response.data?.msg ||
          reason.message ||
          `请求失败，HTTP状态码：${reason.response.status}`
      );
    } else if (
      reason &&
      typeof reason === "object" &&
      reason.status &&
      reason.status !== 200
    ) {
      showGlobalErrorModal(
        reason.msg || reason.detail || `请求失败，HTTP状态码：${reason.status}`
      );
    } else if (
      reason &&
      typeof reason === "object" &&
      (reason.msg || reason.detail)
    ) {
      showGlobalErrorModal(reason.msg || reason.detail);
    } else if (typeof reason === "string") {
      showGlobalErrorModal(reason);
    } else {
      showGlobalErrorModal("发生未知异常");
    }
  });

  window.addEventListener("error", function (event) {
    if (event.error && event.error.msg) {
      showGlobalErrorModal(event.error.msg);
    } else {
      showGlobalErrorModal("发生未知异常");
    }
  });
}
